package com.haha.community.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.haha.community.dao.DiscussPostMapper;
import com.haha.community.entity.Comment;
import com.haha.community.dao.CommentMapper;
import com.haha.community.service.CommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.haha.community.util.CommunityConstant;
import com.haha.community.util.SensitiveFilterUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.util.HtmlUtils;

import java.util.List;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Yang
 * @since 2020-10-30
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService, CommunityConstant {
    @Autowired
    private SensitiveFilterUtil sensitiveFilterUtil;
    @Autowired
    private DiscussPostMapper discussPostMapper;

    @Override
    public List<Comment> findCommentsByEntity(int entityType, int entityId, int offset, int limit) {

        return baseMapper.selectCommentsByEntity(entityType,entityId,offset,limit);
    }

    @Override
    public int findCommentCount(int entityType, int entityId) {
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("entity_type",entityType);
        queryWrapper.eq("entity_id",entityId);
        return baseMapper.selectCount(queryWrapper);
    }

    @Override
    @Transactional
    public int addComment(Comment comment) {
        if (comment == null) {
            throw new IllegalArgumentException("参数不能为空!");
        }
        // 添加评论
        comment.setContent(HtmlUtils.htmlEscape(comment.getContent()));
        comment.setContent(sensitiveFilterUtil.filter(comment.getContent()));
        int row = baseMapper.insert(comment);

        // 更新帖子评论数量
        if (comment.getEntityType() == ENTITY_TYPE_POST) {
            //直接在原来的帖子上面加一
            discussPostMapper.increaseCountById(comment.getEntityId(),row);
            // int count = commentMapper.selectCountByEntity(comment.getEntityType(), comment.getEntityId());
            // discussPostService.updateCommentCount(comment.getEntityId(), count);

        }
        return row;
    }
}
